import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive_flutter/hive_flutter.dart';

import '../lib/common/entity/share.dart';
import '../lib/common/entity/user.dart';
import '../lib/common/services/share_service.dart';
import '../lib/common/services/user_service.dart';
import '../lib/providers/share_provider.dart';
import '../lib/providers/user_provider.dart';

void main() {
  group('ShareAuthorProvider Tests', () {
    late ProviderContainer container;

    setUpAll(() async {
      // 初始化Hive（内存模式用于测试）
      Hive.init('test');
      
      // 注册适配器
      if (!Hive.isAdapterRegistered(0)) {
        Hive.registerAdapter(UserEntityAdapter());
      }
      if (!Hive.isAdapterRegistered(1)) {
        Hive.registerAdapter(ShareEntityAdapter());
      }
      
      // 初始化服务
      await UserService.initialize();
      await ShareService.initialize();
    });

    setUp(() {
      container = ProviderContainer();
    });

    tearDown(() {
      container.dispose();
    });

    tearDownAll(() async {
      await Hive.deleteFromDisk();
    });

    test('should get correct share author', () async {
      // 创建测试分享
      final testShare = ShareEntity(
        id: 'test_share_1',
        description: 'Test share',
        image: 'test.jpg',
        emotion: 'happy',
        date: DateTime.now().toIso8601String(),
        commentIds: [],
        browses: 0,
      );

      // 创建测试用户
      final testUser = UserEntity(
        id: 'test_user_1',
        username: 'testuser',
        password: 'password',
        avatar: 'test_avatar.jpg',
        share: ['test_share_1'], // 包含测试分享ID
        isVip: false,
        like: [],
      );

      // 保存测试数据
      await ShareService.createShare(testShare);
      await UserService.updateUser(testUser);

      // 使用Provider获取作者信息
      final author = container.read(shareAuthorProvider(testShare));

      // 验证结果
      expect(author, isNotNull);
      expect(author!.id, equals('test_user_1'));
      expect(author.username, equals('testuser'));
      expect(author.avatar, equals('test_avatar.jpg'));
    });

    test('should update author info when user info changes', () async {
      // 创建测试分享
      final testShare = ShareEntity(
        id: 'test_share_2',
        description: 'Test share 2',
        image: 'test2.jpg',
        emotion: 'happy',
        date: DateTime.now().toIso8601String(),
        commentIds: [],
        browses: 0,
      );

      // 创建测试用户
      final testUser = UserEntity(
        id: 'test_user_2',
        username: 'oldusername',
        password: 'password',
        avatar: 'old_avatar.jpg',
        share: ['test_share_2'],
        isVip: false,
        like: [],
      );

      // 保存测试数据
      await ShareService.createShare(testShare);
      await UserService.updateUser(testUser);

      // 获取初始作者信息
      final initialAuthor = container.read(shareAuthorProvider(testShare));
      expect(initialAuthor!.username, equals('oldusername'));
      expect(initialAuthor.avatar, equals('old_avatar.jpg'));

      // 更新用户信息
      final updatedUser = testUser.copyWith(
        username: 'newusername',
        avatar: 'new_avatar.jpg',
      );
      await UserService.updateUser(updatedUser);

      // 触发用户Provider状态更新
      await container.read(userProvider.notifier).updateUser(updatedUser);

      // 重新获取作者信息，应该反映最新的用户信息
      final updatedAuthor = container.read(shareAuthorProvider(testShare));
      expect(updatedAuthor!.username, equals('newusername'));
      expect(updatedAuthor.avatar, equals('new_avatar.jpg'));
    });

    test('should return fallback user when author not found', () async {
      // 创建一个没有对应作者的分享
      final orphanShare = ShareEntity(
        id: 'orphan_share',
        description: 'Orphan share',
        image: 'orphan.jpg',
        emotion: 'sad',
        date: DateTime.now().toIso8601String(),
        commentIds: [],
        browses: 0,
      );

      await ShareService.createShare(orphanShare);

      // 获取作者信息，应该返回默认用户
      final author = container.read(shareAuthorProvider(orphanShare));
      
      expect(author, isNotNull);
      // 应该返回默认用户或临时用户
      expect(author!.username, isNotNull);
    });

    test('ShareService.getShareAuthor should work correctly', () async {
      // 创建测试数据
      final testShare = ShareEntity(
        id: 'service_test_share',
        description: 'Service test share',
        image: 'service_test.jpg',
        emotion: 'happy',
        date: DateTime.now().toIso8601String(),
        commentIds: [],
        browses: 0,
      );

      final testUser = UserEntity(
        id: 'service_test_user',
        username: 'serviceuser',
        password: 'password',
        avatar: 'service_avatar.jpg',
        share: ['service_test_share'],
        isVip: true,
        like: [],
      );

      await ShareService.createShare(testShare);
      await UserService.updateUser(testUser);

      // 直接测试ShareService方法
      final author = ShareService.getShareAuthor(testShare);

      expect(author, isNotNull);
      expect(author!.id, equals('service_test_user'));
      expect(author.username, equals('serviceuser'));
      expect(author.isVip, isTrue);
    });
  });
}
